﻿using System.Configuration;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Configuration;

namespace Marbles.Core.Web.Controls
{
    [DefaultProperty("Text")]
    [ToolboxData("<{0}:AnalogClock runat=server></{0}:AnalogClock>")]
    public class AnalogClock : WebControl
    {

        public int AutoRefreshInterval
        {
            get
            {
                object obj = ViewState["UpdateIntervalSeconds"];
                if (obj == null) { return 60; }
                return Convert.ToInt32(obj);
            }
            set { ViewState["UpdateIntervalSeconds"] = value; }
        }

        public bool AutoRefresh
        {
            get
            {
                object obj = ViewState["AutoRefresh"];
                if (obj == null) { return false; }
                return Convert.ToBoolean(obj);
            }
            set { ViewState["AutoRefresh"] = value; }
        }
        
        protected override void CreateChildControls()
        {

            Images.ClockImageHandler.RegisterHttpHandler("Clock.axd", "Marbles.Core.Web.Images.ClockImageHandler", "GET,HEAD");
            Image img = new Image();
            img.ID = this.ClientID + "_Image";
            img.Width = this.Width;
            img.Height = this.Height;
            img.ToolTip = this.ToolTip;
            img.ImageUrl = GetImageUrl();
            this.Controls.Add(img);

            if (AutoRefresh)
            {
                this.Controls.Add(CreateRefreshScript(img.ClientID));

            }
        }

        private string GetImageUrl()
        {
            return string.Format("Clock.axd?w={0}&h={1}", this.Width.Value, this.Height.Value);
        }

        private LiteralControl CreateRefreshScript(string ImageId)
        {
            LiteralControl lt = new LiteralControl();
            StringBuilder sb = new StringBuilder();
            lt.ID = this.ClientID + "_Script";

            sb.Append("<script language=\"javascript\">");
            sb.Append(string.Format("function {0}_Refresh()", this.ClientID));
            sb.Append("{");
            sb.Append("var dte = new Date();");
            sb.AppendFormat("document.getElementById('{0}').src = '{1}&' + dte.getTime();", ImageId, GetImageUrl());
            sb.Append("}");
            sb.Append(string.Format("self.setInterval('{0}_Refresh()', {1});", this.ClientID, (AutoRefreshInterval * 1000)));
            sb.Append("</script>");

            lt.Text = sb.ToString();
            return lt;
        }
    }
}
